import { defineStore } from 'pinia';

export const scgn = defineStore('shouc', {
  state: () => ({
    shoucs: [] as any[], // 存储收藏商品
  }),
  actions: {
    // 添加商品到收藏
    addToFavorites(scData: any) {
      // 检查商品是否已存在于收藏列表
      if (!this.shoucs.some((item) => item.id === scData.id)) {
        this.shoucs.push(scData);
        this.saveToLocalStorage(); // 更新本地存储
      }
    },

    // 从收藏中移除商品
    removeFromFavorites(id: string) {
      this.shoucs = this.shoucs.filter((item) => item.id !== id);
      this.saveToLocalStorage(); // 更新本地存储
    },

    // 保存数据到本地存储
    saveToLocalStorage() {
      localStorage.setItem('shoucs', JSON.stringify(this.shoucs));
    },

    // 从本地存储加载数据
    loadFromLocalStorage() {
      const storedFavorites = localStorage.getItem('shoucs');
      if (storedFavorites) {
        this.shoucs = JSON.parse(storedFavorites);
      }
    },

    // 清空收藏数据
    clearFavorites() {
      this.shoucs = [];
      this.saveToLocalStorage(); // 清空本地存储
    },
  },
});
